package com.runshu.newsmartark.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.idata.extension.IFlyCollectorExt;
import com.runshu.newsmartark.base.BoxBaseActivity;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.common.CMD;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventBusUtils;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.util.y.nativelog.NLogUtil;


import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 * 柜子自检，记录远程日志
 */
public class SelfCheckService extends Service {
    int refreshAllDataTime = 15 * 60 * 1000;

    SyncDataTask task;

    @Override
    public void onCreate() {
        super.onCreate();
        initBox();
        task = new SyncDataTask();
        task.start();
        initReceiver();
    }

    private void initBox() {
        try {
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            try {
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }

    //柜子操作相关接收
    private LocalBroadcastManager lbm;

    private void initReceiver() {
        lbm = LocalBroadcastManager.getInstance(this);
        IntentFilter itent = new IntentFilter();
        itent.addAction(CMD.CloseDoorBroadcast);
        itent.addAction(CMD.OpenDoorBroadcast);
        itent.addAction(CMD.InventoryBroadcast);
        lbm.registerReceiver(receiver, itent);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            Log.e("Receive", "Enter here ，action =="+action);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                UserInfoEntity userInfoGlob = MyApplication.getUserInfoGlob();
//                JSONObject jsonObject = new JSONObject();
                switch (Objects.requireNonNull(action)) {
                    case CMD.CloseDoorBroadcast:
                        //门关了
//                        jsonObject.put("operate", "closeDoor");
//                        jsonObject.put("user", userInfoGlob == null ?
//                                "none/manual" : "<id>" + userInfoGlob.getId() +
//                                "<name>" + userInfoGlob.getUsername() +
//                                "<usrCode>" + userInfoGlob.getUsercode() +
//                                (openTime == 0 ? "" :
//                                        "本次开门最低时长" + ((System.currentTimeMillis() - openTime) / 1000 / 60) + "分钟"));
//                        NLogUtil.i(NLogUtil.INFO_OPERATE_Box, jsonObject.toString());
//                        openTime = 0;
                        break;
                    case CMD.OpenDoorBroadcast:
//                        门开了
//                        openTime = System.currentTimeMillis();
//                        jsonObject.put("operate", "openDoor");
//                        jsonObject.put("user", userInfoGlob == null ?
//                                "none/manual" : "<id>" + userInfoGlob.getId() +
//                                "<name>" + userInfoGlob.getUsername() +
//                                "<usrCode>" + userInfoGlob.getUsercode());
//                        NLogUtil.i(NLogUtil.INFO_OPERATE_Box, jsonObject.toString());
                        break;

                    case CMD.InventoryBroadcast:
//                        jsonObject.put("operate", "scanGoods");
//                        jsonObject.put("user", userInfoGlob == null ?
//                                "none/manual" : "<id>" + userInfoGlob.getId() +
//                                "<name>" + userInfoGlob.getUsername() +
//                                "<usrCode>" + userInfoGlob.getUsercode());
//                        NLogUtil.i(NLogUtil.INFO_OPERATE_Box, jsonObject.toString());

                        break;
                    default:
                        break;
                }
            }
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Toast.makeText(SelfCheckService.this, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
        }
    };

    private void showToast(String msg) {
        Message msg1 = new Message();
        Bundle data = new Bundle();
        data.putString("msg", msg);
        msg1.setData(data);
        handler.sendMessage(msg1);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        initBox();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        task.stop();
        task = null;
        if (lbm != null)
            lbm.unregisterReceiver( receiver );
    }

    long openTime = 0;

    public class SyncDataTask extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                while (true) {
                    sleep(1000 * 60 * 15);
                    //定时的自检 todo
                    if (BoxBaseActivity.ctx!=null)
                    if (BoxBaseActivity.ctx.isCloseDoor()) {
                        if (openTime == 0) {
                            openTime = System.currentTimeMillis();
                        } else {
                            long time = (System.currentTimeMillis() - openTime) / 1000 / 60;
                            if (time > 60) {
                                NLogUtil.w(NLogUtil.Warn_OPEN_TOO_LONG, "（1小时以上提醒）柜子已打开" + time + "分钟");
                            }
                        }
                    } else {
                        openTime = 0;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
